package com.riekoff.particlecubeworld.editor;

import cc.creativecomputing.graphics.CCDrawMode;
import cc.creativecomputing.graphics.CCGraphics;
import cc.creativecomputing.graphics.shader.CCGLSLShader;
import cc.creativecomputing.graphics.shader.CCShaderBuffer;
import cc.creativecomputing.graphics.texture.CCTexture2D;
import cc.creativecomputing.graphics.texture.CCTexture.CCTextureTarget;
import cc.creativecomputing.io.CCIOUtil;
import cc.creativecomputing.util.CCFormatUtil;

public class ATileTexture{
	private CCGLSLShader _myValueShader;
	
	private CCShaderBuffer _myPatternBuffer;
	
	public ATileTexture(ATilePattern thePattern, CCGraphics g){
		_myValueShader = new CCGLSLShader(
			CCIOUtil.classPath(this, "valueShader_vert.glsl"), 
			CCIOUtil.classPath(this, "valueShader_frag.glsl")
		);
		_myValueShader.load();
		_myPatternBuffer = new CCShaderBuffer(thePattern.width * 3,thePattern.height,CCTextureTarget.TEXTURE_RECT);
		
		addPattern(thePattern, g);
	}
	
	public void addPattern(ATilePattern thePatter, CCGraphics g){
		_myPatternBuffer.clear();
		
		_myPatternBuffer.beginDraw();
		_myValueShader.start();
		g.noBlend();
		g.beginShape(CCDrawMode.POINTS);
		for(int x = 0; x < thePatter.width; x++){
			for(int y = 0; y < thePatter.height; y++){
				
				g.textureCoords(
					0,
					thePatter.horizontals[x][y] ? 1f : 0,
					thePatter.verticals[x][y] ? 1f : 0,
					thePatter.tileindices[x][y]
				);
				g.vertex(x,y);
			}
		}
		for(int x = 0; x < thePatter.width; x++){
			for(int y = 0; y < thePatter.height; y++){
				
				g.textureCoords(
					0,
					thePatter.tileX[x][y],
					thePatter.tileY[x][y],
					thePatter.tileOffset[x][y]
				);
				g.vertex(x + thePatter.width,y);
			}
		}
		for(int x = 0; x < thePatter.width; x++){
			for(int y = 0; y < thePatter.height; y++){
				int px1 = (x - 0 + thePatter.width) % thePatter.width;
				int py1 = (y - 1 + thePatter.height) % thePatter.height;
				int px2 = (x - 1 + thePatter.width) % thePatter.width;
				int py2 = (y - 0 + thePatter.height) % thePatter.height;
				
				g.textureCoords(
					0,
					thePatter.horizontals[px1][py1] ? 1f : 0,
					thePatter.verticals[px2][py2] ? 1f : 0,
					0
				);
				g.vertex(x + thePatter.width * 2,y);
			}
		}
		g.endShape();
		_myValueShader.end();
		_myPatternBuffer.endDraw();
	}
	
	public CCTexture2D pattern(){
		return _myPatternBuffer.attachment(0);
	}
}